#include "CSystem.h"
#include "..\Includes\IPhysics.h"
#include "CVector3.h"
#include "..\ParticleMotion\CGravityForceGenerator.h"
using namespace Core;
using namespace std;


CSystem* CSystem::pInstance = 0;


CSystem* CSystem::getInstance()
{
  if (0 == pInstance)
  {
    pInstance = new CSystem();
  }
  return pInstance;
}

void CSystem::destroy()
{
  if (pInstance)
  {
    delete pInstance;
  }
}

CSystem::CSystem()
{
	forceRegistrations=CForceRegister::getForceRegisterInstance();
}

CSystem::~CSystem()
{
  delete forceRegistrations;

}

void CSystem::add(CEntity* pEnt)
{
  entities.push_back(pEnt);
}

void CSystem::update(float dT)
{
  /*for (list<CEntity*>::iterator it = entities.begin(); it != entities.end(); ++it)
  {
    (*it)->applyGravity(dT);
  }*/

  forceRegistrations->update(dT);

}

void CSystem::clean()
{
  for (std::list<CEntity*>::iterator it = entities.begin();it!= entities.end();++it)
  {
    CEntity* pEnt = (*it);
    delete pEnt;
  }
  entities.clear();
  forceRegistrations = 0;
}

void calculatePhysics(real dT)
{
  Core::CSystem::getInstance()->update(dT);
}






//create entity
IEntity* createEntity()
{
	CEntity *  newEntity=new CEntity(0.0f,0.0f,0.0f);
	CSystem::getInstance()->add(newEntity);
	return newEntity;
}

IEntity* createEntity(float posX,float posY,float posZ)
{
	CEntity *  newEntity=new CEntity(posX,posY,posZ);
	CSystem::getInstance()->add(newEntity);
	return newEntity;
}

int createGravityForce(float gravityX,float gravityY,float gravityZ)
{
	return CForceRegister::getForceRegisterInstance()->addForceGenerator(new ParticleMotion::CGravityForceGenerator(Vector3(gravityX,gravityY,gravityZ)));
}

void cleanPhysics()
{
  CSystem::getInstance()->clean();
  CSystem::destroy();
  CForceRegister::getForceRegisterInstance()->clear();
  CForceRegister::destroy();
}